package com.funcablaze.component.view;

import com.funcablaze.component.control.Graphic;
import com.funcablaze.component.control.Graphic2D;
import com.funcablaze.component.control.Theme;
import com.funcablaze.func.AttributeConverter;
import com.funcablaze.func.Color;
import com.funcablaze.window.Frame;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class View extends Component {
	
	protected final List<View> children = new ArrayList<>();
	protected Color background = new Color(0, 0, 0, 0);
	
	public View() {}
	
	/**
	 * 添加子元素
	 * @param child 子元素
	 */
	public void addChild(View child) {
		children.add(child);
	}
	
	public void draw(Graphic graphic, Theme.ThemeType theme) {
		_draw(graphic, theme);
		for (View child : children) {
			child._draw(graphic, theme);
		}
	}
	
	@Override
	public void _draw(Graphic graphic, Theme.ThemeType theme) {
		graphic.setColor(background);
		graphic.drawRect(x, y, width, height);
	}
	
	/**
	 * 应用属性
	 * @param attrs 属性
	 */
	public static void applyAttributes(View view, Map<String, String> attrs) {
		Class<?> clazz = view.getClass();
		attrs.forEach((attrName, value) -> {
			try {
				// 转换命名风格：background-color -> backgroundColor
				String fieldName = AttributeConverter.toCamelCase(attrName);
				
				// 优先使用setter方法
				String setterName = "set" + view.capitalize(fieldName);
				Method setter = AttributeConverter.findSetter(clazz, setterName, value);
				
				if (setter != null) {
					Class<?> paramType = setter.getParameterTypes()[0];
					Object converted = AttributeConverter.convert(value, paramType);
					setter.invoke(view, converted);
				} else {
					// Fallback到字段反射
					Field field = clazz.getDeclaredField(fieldName);
					field.setAccessible(true);
					Object converted = AttributeConverter.convert(value, field.getType());
					field.set(view, converted);
				}
			} catch (Exception e) {
				AttributeConverter.handleError(attrName, value, e);
			}
		});
	}
	
	/**
	 * 首字母大写
	 * @param fieldName 字段名 text-view -> TextView
	 * @return 首字母大写的字段名
	 */
	private String capitalize(String fieldName) {
		return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
	}
	
	/**
	 * 设置背景色
	 * @param hex 十六进制颜色值
	 */
	public void setBackground(String hex) {
		this.background = new Color(hex);
	}
}
